package com.hk.core.jdbc.dialect;

import com.hk.commons.util.StringUtils;

/**
 * 数据库分页方言
 *
 * @author kevin
 * @date 2018-09-19 10:05
 * @see OracleDialect
 */
@FunctionalInterface
public interface Dialect {

    String getLimitSql(String sql, int offset, int rows);

    /**
     * Mysql
     */
    static Dialect mysql() {
        return (sql, offset, rows) -> String.format("%s LIMIT %d,%d", sql, offset, rows);
    }

    /**
     * postgre Sql
     */
    static Dialect postgreSql() {
        return (sql, offset, rows) -> String.format("%s LIMIT %d OFFSET %d", sql, rows, offset);
    }

    /**
     * sybase，没有分页语句，用top查询后，通过 ResultSet.absolute 方法过滤数据
     * 但这里没有实现，可以参考: <a href="https://gitee.com/kevin-core/zhitong-parent/blob/master/zhitong-console/src/main/java/com/hk/zhitong/console/service/impl/SqlAnywhereSourceHandler.java">skipRows</a>
     */
    static Dialect sybase() {
        return (sql, offset, rows) -> {
            sql = sql.substring(7);// 去掉开始的SELECT
            return String.format("SELECT TOP %d %s", rows, sql);
        };
    }

    /**
     * SQL Server
     */
    static Dialect sqlServer() {
        return (sql, offset, rows) -> {
            if (!StringUtils.containsIgnoreCase(sql, "order by")) {
                sql += " ORDER BY (SELECT 0)";
            }
            return String.format("%s OFFSET %d ROWS FETCH NEXT %d ROWS ONLY", sql, offset, rows);
        };
    }
}
